package com.syf.config.result;

import com.syf.config.annotation.CommonResult;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @desc 接口响应体控制拦截器【拦截器处理逻辑】
 *
 * @author syf
 */
public class ResponseResultInterceptor implements HandlerInterceptor {

  	//req中注解的Key
	public static final String RESPONSE_RESULT = "RESPONSE-RESULT";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (handler instanceof HandlerMethod) {  //是否是 方法处理器
			final HandlerMethod handlerMethod = (HandlerMethod) handler;
			final Class<?> clazz = handlerMethod.getBeanType(); //Bean类型
			final Method method = handlerMethod.getMethod(); //方法对象
			if (clazz.isAnnotationPresent(CommonResult.class)) { //该类上有@CommonResult注解
				request.setAttribute(RESPONSE_RESULT, clazz.getAnnotation(CommonResult.class)); //将该注解对象存储进req中
			} else if (method.isAnnotationPresent(CommonResult.class)) { //该方法上使用了 @CommonResult注解
				request.setAttribute(RESPONSE_RESULT, method.getAnnotation(CommonResult.class));
			}
		}

		return true;
	}



}
